package com.kyomonn.talkischeap;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class RegisterActivity extends AppCompatActivity {

    private EditText etUsername, etPassword, etConfirmPassword;
    private TextView etEmail, tvMessage;

    private MySQLiteOpenHelper mySQLiteOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 绑定视图
        etUsername = findViewById(R.id.et_username_register);
        etPassword = findViewById(R.id.et_password_register);
        etConfirmPassword = findViewById(R.id.et_confirm_password);
        Button btnRegister = findViewById(R.id.btn_register);
        etEmail = findViewById(R.id.et_email);
        tvMessage = findViewById(R.id.tv_message);

        // 注册点击事件
        btnRegister.setOnClickListener(v -> registerUser());
    }

    private void registerUser() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        String email = etEmail.getText().toString().trim();

        mySQLiteOpenHelper = new MySQLiteOpenHelper(this, "LocalStorage.db", null, 1);
        SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase();
        String sql = "select * from users where username = ?";
        Cursor cursor = db.rawQuery(sql, new String[]{username});
        if (cursor.moveToFirst()) {
            cursor.close();
            tvMessage.setText("用户名已存在");
            return;
        }
        cursor.close();

        if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty() || email.isEmpty()) {
            tvMessage.setText("所有字段都不能为空");
            return;
        }

        if (!password.equals(confirmPassword)) {
            tvMessage.setText("两次输入的密码不一致");
            return;
        }

        sql = "insert into users(username, password, email) values(?,?,?)";
        db.execSQL(sql, new String[]{username, password, email});
        db.close();

        Toast.makeText(this, "注册成功！用户名：" + username, Toast.LENGTH_SHORT).show();

        Intent data = new Intent();
        data.putExtra("username", username);
        data.putExtra("password", password);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mySQLiteOpenHelper.close();
    }
}
